from django.shortcuts import render
from rest_framework import generics, mixins
from rest_framework.views import APIView
# from dbs_insert.models import *
from dbs_insert import serializers, models
from public import tools
from public.tools import response_origin
import datetime
from rest_framework.decorators import api_view
import json
from rest_framework.response import Response


# Create your views here.
@api_view(http_method_names=['GET'])
def health(data):
    content={}
    data = {'status': 'UP'}
    content['payload'] = {"data",json.dumps(data)}
    content['status'] = 1
    content['errmsg'] = ""
    return Response(data)


class CreateTopicView(generics.ListCreateAPIView):
    queryset = models.DfeTopic.objects.all()
    serializer_class = serializers.TopicDetailSerializer

    def post(self, request, *args, **kwargs):
        try:
            content = tools.make_standard_dict()
            data = tools.is_data(request, "POST", "project_id", "topic_name", "partition_number", "creator_id")
            # print(data)
            if not isinstance(data, dict):
                return data
            t_name = tools.check_topic(data["topic_name"], data["project_id"])
            if not tools.create_topic(data["topic_name"], data["partition_number"]):
                content = tools.make_false_dict()
                content["errmsg"] = "创建Topic失败"
                return response_origin(content)
            ctopic = models.DfeTopic()
            ctopic.project_id = data["project_id"]
            ctopic.project_name = models.DfeProject.objects.get(project_id=data['project_id']).project_name
            ctopic.topic_code = models.DfeTopic.objects.last().topic_code + 1
            ctopic.topic_name = t_name
            ctopic.partition_number = data["partition_number"] if 2 < int(data["partition_number"]) < 7 else 3
            ctopic.creator_id = data["creator_id"]
            ctopic.copy_number = 5
            ctopic.create_time = datetime.datetime.now()
            ctopic.update_time = datetime.datetime.now()
            ctopic.save()
            content["payload"]["topic_name"] = t_name
            return response_origin(content)
        except Exception as e:
            content = tools.make_false_dict()
            content["errmsg"] = str(e)
            return response_origin(content)


class CreateDatabasesView(generics.ListCreateAPIView):
    queryset = models.DfeTopic.objects.all()
    serializer_class = serializers.TopicDetailSerializer

    def get(self, request, *args, **kwargs):
        return response_origin({"message": "请输入信息"})

    def post(self, request, *args, **kwargs):
        try:
            content = tools.make_standard_dict()
            serializer = serializers.DatabaseSerializer(data=request.data)
            if serializer.is_valid():
                data = dict(serializer.validated_data)
                cont = tools.create_db(data["db_type"], data["project_id"])
                if cont != "True":
                    return response_origin(cont)
                db_name = "db_" + str(data["project_id"])
                cdb = models.DfeDatabase()
                cdb.project_id = data["project_id"]
                cdb.project_name = models.DfeProject.objects.get(project_id=data['project_id']).project_name
                cdb.database_type = data["db_type"]
                cdb.database_name = db_name
                cdb.create_time = datetime.datetime.now()
                cdb.creator_id = data["creator_id"]
                cdb.update_time = datetime.datetime.now()
                cdb.save()
                content["payload"]["db_name"] = db_name
                return response_origin(content)
        except Exception as e:
            content = tools.make_false_dict()
            content["errmsg"] = str(e)
            return response_origin(content)


class CreateTableView(generics.ListCreateAPIView):
    queryset = models.DfeTable.objects.all()
    serializer_class = serializers.TableSerializer

    def get(self, request, *args, **kwargs):
        return response_origin({"message": "请输入信息"})

    def post(self, request, *args, **kwargs):
        try:
            content = tools.make_standard_dict()
            data = tools.is_data(request, "POST", "project_id", "db_name", "schema", "tb_name", "db_type","topic_name")
            if not isinstance(data, dict):
                return data
            if not models.DfeTopic.objects.filter(project_id=data["project_id"],topic_name=data["topic_name"]).exists():
                content["errmsg"] = "此Topic名称不存在!"
                return response_origin(content)
            tools.create_table(eval(data["schema"].encode("utf-8")), data["tb_name"], data["db_type"], data["db_name"])
            ctable = models.DfeTable()
            ctable.file_id = 3
            ctable.project_id = data["project_id"]
            ctable.project_name = models.DfeProject.objects.get(project_id=data['project_id']).project_name
            ctable.database_id = models.DfeDatabase.objects.get(project_id=data["project_id"],
                                                                database_name=data["db_name"]).database_id
            ctable.database_name = data["db_name"]
            ctable.create_type = 0
            ctable.topic_name = data["topic_name"]
            ctable.topic_id = models.DfeTopic.objects.get(project_id=data["project_id"],
                                                          topic_name=data["topic_name"]).topic_id
            ctable.manger_id = 32
            ctable.manager_name = 1213
            ctable.create_type = 1
            ctable.table_name = data["tb_name"]
            ctable.create_time = datetime.datetime.now()
            ctable.update_time = datetime.datetime.now()
            ctable.save()
            content["payload"]["message"] = "创建成功！"
            return response_origin(content)
        except Exception as e:
            content = tools.make_false_dict()
            content["errmsg"] = str(e)
            return response_origin(content)
